const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const path = require('path');
const { sequelize } = require('./models');
const { logger, requestLogger, logError } = require('./utils/logger');

const app = express();

// 数据库连接测试
sequelize.authenticate()
  .then(() => logger.info('Database connected'))
  .catch(err => logger.error('Database connection error:', err));

// 中间件
app.use(cors());
app.use(helmet());
app.use(morgan('dev'));
app.use(express.json());
app.use(requestLogger);
app.use(express.urlencoded({ extended: true }));

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// API路由（抽离后的路由配置）
app.use('/api', require('./routes'));

// 错误处理中间件
app.use((err, req, res, next) => {
  logError(err, {
    path: req.path,
    method: req.method
  });
  res.status(500).send('Server Error');
});

module.exports = app;